#include <iostream>
#include <vector>
#include <assert.h>
#include <pthread.h>
#include <unistd.h>

#define THREAD_NUM 10

using namespace std;

class ThreadData
{
public:
    pthread_t tid;
    char namebuffer[64];
    long long number;
};

class ThreadReturn
{
public:
    int number;
    int exit_code;
};
void* start_routine(void* args)
{
    sleep(1);
    int cnt = 10;
    ThreadData* td = static_cast<ThreadData *>(args);
    while(cnt--)
    {
        cout << "new thread name:" << td->namebuffer << " cnt:" << cnt << endl;
        sleep(1);
    }

    // ThreadReturn* ret = new ThreadReturn;
    // ret->exit_code = 0;
    // ret->number = td->number;
    // delete td;

    
    pthread_exit((void*)666);
    // return (void*)td->number;
}

int main()
{
    vector<ThreadData*> threads;

    //线程创建
    for(int i = 1; i <= THREAD_NUM;i++)
    {
        ThreadData* td = new ThreadData;
        td->number = i;
        snprintf(td->namebuffer,sizeof(td->namebuffer),"%s:%d","thread",i);
        pthread_create(&td->tid,nullptr,start_routine,td);
        threads.push_back(td);
    }

    for(auto& e : threads)
    {
        cout << "make thread success, name:" << e->namebuffer << " tid:" << e->tid << endl;
    }

    sleep(5);
    //线程取消
    //取消退出码为-1，PTHREAD_CANCELED
    for(int i = 0;i < threads.size()/2; i++)
    {
        pthread_cancel(threads[i]->tid);
    }

    for(auto& it : threads)
    {
        void* ret = 0;
        int n = pthread_join(it->tid,&ret);
        assert(n == 0);
        cout << "join " << it->namebuffer << " success, exit code: " << (long long)ret << endl;
        delete it;
    }

    // for(auto& it : threads)
    // {
    //     //线程等待信息
    //     ThreadReturn* ret = nullptr;
    //     int n = pthread_join(it->tid,(void**)&ret);
    //     assert(n == 0);
    //     cout << "join " << it->namebuffer << " success,number: " << ret->number << ", exit code: " << ret->exit_code << endl;
    //     delete ret;
    //     delete it;
    // }

    cout << "main pthread quit" << endl;
    // while(true)
    // {
    //     cout << "main thread" << endl;
    //     sleep(1);
    // }
    return 0;
}





